import router from '@/router';
import store from '@/store';
import http from './http';
import {baseUrl, appid} from './config';
import { Toast } from 'vant';

function util() {
    this.baseUrl = baseUrl;

    this.checkLogin = (type)=> {
        let accessToken = localStorage.getItem('access_token');
        if(!accessToken){
          if(type == 'nologin'){
            console.log('不跳转登录')
          }else{
            Dialog.alert({
                title: '登录失效，请重新登录！',
                message: msg,
              }).then(() => {
                localStorage.clear();
                router.push({path: '/login/index'});
              });
          }          
          return false;
        }
        return true;
        
    }
    
    this.gotoPage = (path, query) =>{
        let params = {path: path};
        if(query){
            params.query = query;
        }
        router.push(params);
    };

    // 序列化转为对象
    this.format = (str) => {
        let arr = str.split('&');
        let obj = {};
        arr.forEach(item => {
            let item_arr = item.split('=')
            obj[item_arr[0]] = item_arr[1];
        });
        return obj;
    };

    // 对象转为序列化
    this.serialize = (obj) => {
        let str = '?';
        for(let key in obj){
            str += key + '=' + obj[key] + '&';
        };
        return str.slice(0, str.length-1);
    }

    // 号码脱敏
    this.desNumber = (num, char) => {
        if(!num){
            return ''
        }
        let str = num.toString();
        let str1 = str.substring(0,3);
        let str2 = str.substring(str.length-3, str.length);
        if(str.length > 6){
            let str1 = str.substring(0,3);
            let str2 = str.substring(str.length-3, str.length);
            return str1 + '******' + str2;
        }else{
            let str1 = str.substring(0,3);
            // let str2 = str.substring(str.length-3, str.length);
            return str1 + '******';
        }
    }

    // 将毫秒转为时分秒
    this.formatDuring = (mss) => {
        var days = parseInt(mss / (1000 * 60 * 60 * 24));
        var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((mss % (1000 * 60)) / 1000);
        let str = '';
        if(hours == 0){
            str = minutes + "分钟 " + seconds + "秒 ";
        }else{
            str = hours + '小时' + minutes + "分钟" + seconds + "秒 ";
        }
        if(hours == 0 && minutes == 0){
            str = seconds + '秒'
        }
        return str;
    };

    // 将时间转为字符串
    this.dateToString = (now) => {
        var year = now.getFullYear();
        var month =(now.getMonth() + 1).toString();
        var day = (now.getDate()).toString();
        var hour = (now.getHours()).toString();
        var minute = (now.getMinutes()).toString();
        var second = (now.getSeconds()).toString();
        if (month.length == 1) {
            month = "0" + month;
        }
        if (day.length == 1) {
            day = "0" + day;
        }
        if (hour.length == 1) {
            hour = "0" + hour;
        }
        if (minute.length == 1) {
            minute = "0" + minute;
        }
        if (second.length == 1) {
            second = "0" + second;
        }
        var dateTime = year + "-" + month + "-" + day +" "+ hour +":"+minute+":"+second;
        return dateTime;
    };

    // 路由跳转
    this.goto = function(url, params = {}, delay = 0) {
        let default_params = {path: url};
        let new_params = Object.assign(default_params,params);
		setTimeout(function() {
			router.push(new_params);
		}, delay);
	};

    
    // 关闭弹窗，弹窗内的表单初始化
    this.resetForm = (form, reset_form) => {
        for(var key in form){
            if(reset_form.hasOwnProperty(key)){
                form[key] = reset_form[key];
            };
        }
    };

    

    // 时间格式兼容性转换
    this.getTime = (data) => {
        let new_date = data.replace(/-/g,"/");
        let time = new Date(new_date).getTime();
        return time;
    };

    // 获取名字
    this.setName = (id, list) => {
        let name = '未知';
        let newList = list || [];
        let arr = newList.filter(item => item.id == id);
        if(arr.length == 1){
            name = arr[0].name;
        }
        return name;          
    }

    //数组格式转化
    this.transformArray = (arr, idKey, nameKey) => {
        let id = idKey || 'value';
        let name = nameKey || 'label';
        let data = [];
        if(arr.length  > 0){
            data = arr.map(item => {
                let obj = item;
                obj.id = item[id];
                obj.name = item[name]
                return obj;
            });
        }else{
            data = []
        }
        return data;
    },

    //对象转数组
    this.objectToArray = (obj1, obj2)=>{
        let arr = [];
        for(let key in obj1){
            arr.push({name: obj1[key], value: obj2[key]})
        }
        return arr;
    }
    // 将数值按某个key，相同的排在一起
    this.sortArray = (arr, key) => {
		let new_arr = [];
		function compare(arr_sub){
			let arr1 = [];
			arr_sub.forEach((item,index) => {
				if(index == 0){
					new_arr.push(item);
					arr1.push(item);
				}else{
					if(item[key] == arr1[0][key]){
						new_arr.push(item);
						arr1.push(item);
					}
				}
			});		
			let arr2 = arr_sub.filter(item => item[key] != arr1[0][key]);
			if(new_arr.length < arr.length){
				compare(arr2, key);
			}
		}
		compare(arr);
		return new_arr;
    }

    //先清空数组，再重新添加数组，使得视图能更新
    this.resetArray = (arr, data) => {
        arr.splice(0, arr.length);
        data.forEach(item => {
            arr.push(item);
        })
    }

    // 根据身份证获取对应的出生日期，年龄，性别
    this.analysisIdNo = (IdCardNO) => {
        let res = {
            age: null,
            birth: null,
            sex: null,
        }
        // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
        var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (reg.test(IdCardNO) === false)
        {
            Message.warning("身份证号输入不合法");
            return res;
        }
        let date = new Date();
        let yearfull = date.getFullYear();
        if (IdCardNO.length == 18)//18位身份证号处理
        {
            let birthyear = IdCardNO.substring(6, 10);
            let month = IdCardNO.substring(10, 12);
            let day = IdCardNO.substring(12, 14);
            let age = yearfull - birthyear;
            let sexValue = IdCardNO.substring(16, 17);
            let sex = (sexValue % 2 == 0 ? "女" : "男");
            if (sex.toString() == "女")
                sexValue = "2";
            if (sex.toString() == "男")
                sexValue = "1";
            else sexValue = "0";
           res.age = age;
           res.sex = sexValue;
           res.birth = birthyear + '-' + month + '-' + day;
        }
        if (IdCardNO.length == 15)//15位身份证号处理
        {
            let birthyear = '19'+IdCardNO.substring(6, 8);
            let month = IdCardNO.substring(8, 10);
            let day = IdCardNO.substring(10, 12);
            let birthDay = "";
            birthDay = IdCardNO.substring(6, 12);
            birthDay = "19" + birthDay;
            birthDay = birthDay.substring(0, 4);// + "-" + birthDay.substring(4, 6) + "-" + birthDay.substring(6)
            let age = yearfull - birthDay;//年龄
            let sex = parseInt(birthDay.substring(14, 1), 10) % 2 ? "男" : "女";//性别
            let sexValue = "";
            if (sex.toString() == "女")
                sexValue = "2";
            if (sex.toString() == "男")
                sexValue = "1";
            else sexValue = "0";
            res.age = age;
            res.sex = sexValue;
            res.birth = birthyear + '-' + month + '-' + day;            
        }
        return res;
    };

    //获取字典
    this.getDictList =  async (type) => {
        let list = [];
        let initData = store.getters.initData || {};
        if (JSON.stringify(initData) != '{}') {
          if (initData.hasOwnProperty(type + '_list')) {
            list = initData[type + '_list'];
          } else {
            let res = await http('get', '/admin/dict/type/' + type, {});
            if (res.length > 0) {
              list = this.transformArray(res);
              initData[type + '_list'] = list;
              store.commit('setInitData', initData);
            }
          }
        } else {
            let res = await http('get', '/admin/dict/type/' + type, {});
            if (res.length > 0) {
              list = this.transformArray(res);
              initData[type + '_list'] = list;
              store.commit('setInitData', initData);
            }
        }
        return new Promise((resolve, reject) => {
            resolve(list);
        });
    },
    
    //浏览器全屏

    this.reqFullScreen = () => {
        if (document.documentElement.requestFullScreen) {
        document.documentElement.requestFullScreen();
        } else if (document.documentElement.webkitRequestFullScreen) {
        document.documentElement.webkitRequestFullScreen();
        } else if (document.documentElement.mozRequestFullScreen) {
        document.documentElement.mozRequestFullScreen();
        }
    };
   //浏览器退出全屏
    this.exitFullScreen = () => {
        if (document.documentElement.requestFullScreen) {
        document.exitFullScreen();
        } else if (document.documentElement.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
        } else if (document.documentElement.mozRequestFullScreen) {
        document.mozCancelFullScreen();
        }
    };

    // 网页微信支付
    this.payWx = (data) => {
        wx.config({
            beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: data.appId, // 必填，公众号的唯一标识
            timestamp: data.timeStamp, // 必填，生成签名的时间戳
            nonceStr: data.nonceStr, // 必填，生成签名的随机串
            signature: data.signature, // 必填，签名
            jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
        });
        wx.ready(() => {
            wx.chooseWXPay({
                timestamp: data.timeStamp,
                nonceStr: data.nonceStr,
                package: data.package,
                signType: data.singType,
                paySign: data.paySign,
                success: res => {

                },
                cancel: res => {
                    Toast('取消支付！')
                },
                fail: res => {
                    Toast.fail('支付失败')
                }
            })
        })
    },
    //拿到微信code
    this.getWxCode = (type = 'userinfo', url) =>{
        //snsapi_userinfo用来获取用户的基本信息的,需要用户手动同意
        //snsapi_base获取进入页面的用户的openid的,静默授权
        let href = window.location.href;
        let code = this.GetParam(href.split("#")[0], "code");
        if (!code) {
            // let url = encodeURIComponent('https://h5.hospital.caochuanxi.com#/login/index');
            // let url = encodeURIComponent('https://h5.hospital.caochuanxi.com');
            let url = encodeURIComponent(href)
            window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appid+'&redirect_uri='+url+'&response_type=code&scope=snsapi_'+type+'&state=STATE#wechat_redirect'
        } else {
            code = this.GetParam(href, "code");
            // http('get', '/admin/bill/getOpenId', {code: code}, (data,msg) => {
            //     if(data.openId){
            //         localStorage.setItem('openId', data.openId);
            //     }
            // });
            return code;
        }
    },
    // 截取code
    this.GetParam = (url, code) => {
        url = url + "";
        let regstr = "/(\\?|\\&)" + code + "=([^\\&]+)/";
        let reg = eval(regstr);
        //eval可以将 regstr字符串转换为 正则表达式
        let result = url.match(reg);
        if (result && result[2]) {
            return result[2];
        }
    }
    
}

export default new util;